/**
 * 
 */
package org.swing.utility.jms.receiver;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import javax.naming.NamingException;

import org.swing.utility.jms.exception.JMSConnectorException;
import org.swing.utility.jms.util.JmsConnector;
import org.swing.utility.jms.util.ParameterRepository;

/**
 * @author lqnhu
 *
 */
public class JmsReceiver {
	private JmsConnector connector = null;

	private JmsReceiver(String subscribe) throws JMSConnectorException {
		connector = JmsConnector.build(subscribe);
	}

	public static JmsReceiver buildForQueue() throws JMSConnectorException {
		return new JmsReceiver(ParameterRepository.SUBSCRIBE_QUEUE);
	}

	public static JmsReceiver buildForTopic() throws JMSConnectorException {
		return new JmsReceiver(ParameterRepository.SUBSCRIBE_TOPIC);
	}

	public String receiveString() throws JMSException, NamingException {
		TextMessage msg = (TextMessage) receive();
		return msg.getText();
	}

	public Object receiveObject() throws JMSException, NamingException {
		ObjectMessage objectMsg = (ObjectMessage) receive();
		return objectMsg.getObject();
	}

	public void close() throws JMSException {
		connector.close();
	}

	private Message receive() throws JMSException, NamingException {
		return connector.getMessageConsumer().receive();
	}
}
